//
//  COCallToolManager.swift
//  CocoProject
//
//  Created by Vill on 2023/11/10.
//

import Foundation
import SwiftyJSON

extension UIViewController{
    
    // 获取用户在线状态  rechargeType:1 跳转wallet控制器  2:弹出（用于个人中心拨打电话金币不足）
    func requestStatus(userId: String,rechargeType : Int = 1) {
        // 判断权限
        let audioStatus = AVCaptureDevice.authorizationStatus(for: .audio)
        let videoStatus = AVCaptureDevice.authorizationStatus(for: .video)
        if audioStatus == .notDetermined || videoStatus == .notDetermined {
            requestAVAuthorization()
            return
        }
        // 权限未开启，提示开启权限
        if !judgeAuthorPermisstion(){
            self.showAlert(style: .alert, title: nil, message: "You are not authorized to access the camera or microphone", actions: ["Click to authorize"]) { type in
                if let url = URL(string:UIApplication.openSettingsURLString) {
                      if #available(iOS 10.0, *) {
                            UIApplication.shared.open(url, options: [:], completionHandler: nil)
                      } else {
                            UIApplication.shared.openURL(url)
                      }
                }
            }
            return
        }
        getUserStatus(userId, rechargeType)
    }
    
    // 请求视频语音权限
    func requestAVAuthorization() {
        let audioStatus = AVCaptureDevice.authorizationStatus(for: .audio)
        let videoStatus = AVCaptureDevice.authorizationStatus(for: .video)
        if audioStatus == .notDetermined {
            AVCaptureDevice.requestAccess(for: .audio) { (granted) in
            }
        }
        if videoStatus == .notDetermined {
            AVCaptureDevice.requestAccess(for: .video) { (granted) in
            }
        }
    }
    
    // 判断权限是否已允许
    func judgeAuthorPermisstion() -> Bool {
        let audioStatus = AVCaptureDevice.authorizationStatus(for: .audio)
        let videoStatus = AVCaptureDevice.authorizationStatus(for: .video)
        if audioStatus == .denied || videoStatus == .denied {
            return false
        }
        return true
    }
    
    // 获取用户在线状态
    func getUserStatus(_ id:String,_ rechargeType : Int){
        UIToolHelper.makeToast("Calling...")
        var params = [String:Any]()
        params["ids"] =  id
        var target = COBaseApi.getListStreamerInfo(param: params)
        let feed = kFeedbackVer.keyGetNSDefaultsKey() as? Bool
        if feed == true{
            target = COBaseApi.getListUserInfo(param: params)
        }
        COHttpManager.request(target: target, modelType: COChatUsersModel.self) {[weak self] code, object, success in
            UIToolHelper.hideHUD()
            let users = object?.users
            if (users?.count ?? 0 > 0){
                let streamer = users?.first
                if (streamer?.status == 1){
                    self?.callWithModel(model: streamer, rechargeType: rechargeType)
                }else if (streamer?.status == 2){
                    UIToolHelper.makeToast("The user is busy")
                }else{
                    UIToolHelper.makeToast("The user is offline")
                }
            }
        } failureBlock: { code, msg in
            UIToolHelper.hideHUD()
            UIToolHelper.makeToast("The user is offline")
        }
    }
    
    //MARK: ----------- 充值弹窗  ------------------
    func goRechargeWithGift(){
        let recharge = CORechargePresentController()
        self.presentBottom(vc: recharge)
    }
    
    //MARK: -------------- 发送礼物 --------------
    func sendGiftMessage(block: @escaping (_ model:COGiftModel) -> Void){
        if (COUserInfoManager.giftsLoaded() == false){
            KAppDelegate.getGiftSearchList()
            return
        }
        COUserInfoManager.getGiftsInfo()     //读取内容
        let gift = COGiftPresentController()
        gift.gifts = COUserInfoManager.shared.gifts?.gift
        self.presentBottom(vc: gift)
        // 去充值
        gift.giftRecharge = { [weak self] in
            guard let `self` = self else { return }
            self.goRechargeWithGift()
        }
        // 送礼物
        gift.giftSend = { giftModel in
            block(giftModel)
        }
    }
    
    // 拨打电话
    func callWithModel(model:DGChatUserInfoModel?,rechargeType : Int){
        // 判断金币是否充足不足则去充值
        let feed = kFeedbackVer.keyGetNSDefaultsKey() as? Bool
        let livecal = kLiveCalling.keyGetNSDefaultsKey() as? Bool
        guard let user = COUserInfoManager.shared.curUser else { return }
        if user.userResponse.balance < model?.price ?? 0 && feed == false{
            let balanceAlert = COBalanceAlertView.init(coins: user.userResponse.balance, subtitle: "You don't have enough balance\nfor one minute")
            balanceAlert.show()
            balanceAlert.certainBlock = {
                DispatchQueue.main.async {
                    if rechargeType == 1{
                        self.navigationController?.pushViewController(COBalanceController(), animated: true)
                    }else{
                        self.goRechargeWithGift()
                    }
                }
            }
            return
        }
        // 给对方发送消息并跳转打电话界面
        let rongcloudId = feed == true ? "client_\(model!.id)" : "streamer_\(model!.id)"
        let msgContent = COVideoContent()
        msgContent.streamerID = Int64(model!.id)
        msgContent.streamerName = model?.name
        msgContent.cost = model?.price
        msgContent.customerID = Int64(user.userResponse.id)
        msgContent.customerName = user.userResponse.nickName
        msgContent.senderUserInfo = RCUserInfo(userId: user.rcUserId, name: user.userResponse.nickName, portrait: user.userResponse.profilePhoto)
        RCIMClient.shared().sendMessage(.ConversationType_PRIVATE, targetId: rongcloudId, content: msgContent, pushContent: "Received a call", pushData: "Received a call") { [weak self](messageId) in
            guard self != nil else {
                return
            }
            if livecal ==  true {
                let params = [
                    "streamerId": model?.id,
                    "customerId": user.userResponse.id
                ]
                let json = JSON(params)
                if let jsonString = json.rawString() {
                    let message = RCCommandMessage(name: "hangup", data: jsonString)
                    RCIMClient.shared().sendMessage(.ConversationType_PRIVATE, targetId: rongcloudId, content: message, pushContent: nil, pushData: nil) { (messageId) in
                        print("== 挂断电话消息发送了 ==")
                    } error: { (errorCode, messageId) in
                        print("\(errorCode.rawValue)" + "\(messageId)")
                    }
                }
                return
            }
            DispatchQueue.main.safeAsync {
                let videoCall = COCallViewController()
                videoCall.anchorModel =  model!
                videoCall.isCalling = true
                UIToolHelper.currentViewController()?.navigationController?.pushViewController(videoCall, animated: true)
                kLiveCalling.keySaveToNSDefaults(with: true)
            }
        } error: { (errorCode, messageId) in
            UIToolHelper.makeToast("Failed to call")
        }
    }
}
